package controller

import (
	"goWeb/bookStore/dao"
	"goWeb/bookStore/model"
	"goWeb/bookStore/utils"
	"html/template"
	"net/http"
	"time"
)

func ToCheckOut(w http.ResponseWriter, r *http.Request) {
	//获取到用户所有的购物车和购物项
	_, session := dao.IsLogin(r)
	cart, _ := dao.GetCartByUserId(session.Userid)
	orderId := utils.CreateUUID()
	createTime := time.Now().Format("2006-01-02 15:04:05")
	//然后组装订单数据和订单项数据
	//1.组装order数据
	order := &model.Order{
		Id:         orderId,
		CreateTime: createTime,
		Tcount:     cart.Tcount,
		Tamout:     cart.Tamout,
		Statu:      0,
		UserId:     session.Userid,
	}
	//然后插入到数据库中
	err := dao.AddOrder(order)
	if err != nil {
		panic(err.Error())
	}
	//2.组装订单项数据
	for _, v := range cart.CartItems {
		orderItem := &model.OrderItem{
			Img_path: v.Books.Img_path,
			Title:    v.Books.Title,
			Author:   v.Books.Author,
			Price:    v.Books.Price,
			Count:    v.Count,
			Amout:    v.Amout,
			OrderId:  orderId,
		}
		err = dao.AddOrderItem(orderItem)
		if err != nil {
			panic(err.Error())
		}
		book := v.Books
		book.Sales += v.Count
		book.Stock -= v.Count
		//去将库存和销量进行更新
		dao.UpdateBook(book)
	}
	//然后清空购物车
	err = dao.EmptyCart(cart.Id)
	if err != nil {
		panic(err.Error())
	}

	session.Order = order
	t := template.Must(template.ParseFiles("views/pages/cart/checkout.html"))
	t.Execute(w, session)
}

//后台订单管理
func OrdersManager(w http.ResponseWriter, r *http.Request) {
	orders, _ := dao.GetAllOrders()
	t := template.Must(template.ParseFiles("views/pages/manager/order_manager.html"))
	t.Execute(w, orders)
}

//查看订单详情
func ToOrderItem(w http.ResponseWriter, r *http.Request) {
	orderid := r.FormValue("orderid")
	orderItems, _ := dao.GetOrderItemByOrderId(orderid)
	// for k, v := range orderItems {
	// 	fmt.Printf("%d个orderItems是%v\n", k, v)
	// }
	t := template.Must(template.ParseFiles("views/pages/order/order-info.html"))
	t.Execute(w, orderItems)

}

//我的购物车
func ToMyOrders(w http.ResponseWriter, r *http.Request) {
	_, session := dao.IsLogin(r)
	orders, _ := dao.GetMyOrder(session.Userid)
	session.Orders = orders
	t := template.Must(template.ParseFiles("views/pages/order/order.html"))
	t.Execute(w, session)
}

//去发货
func ToSendOrders(w http.ResponseWriter, r *http.Request) {
	orderid := r.FormValue("orderid")
	dao.UpdateOrderStatusById(orderid, 1)
	OrdersManager(w, r)
}

//去收货
func ToTakeOrders(w http.ResponseWriter, r *http.Request) {
	orderid := r.FormValue("orderid")
	dao.UpdateOrderStatusById(orderid, 2)
	ToMyOrders(w, r)

}
